package dbops

import (
	"os/exec"
	"time"
	"fmt"
	"bytes"
	"errors"
	"gitee.com/DengAnbang/Wefore/src/code"
	"gitee.com/DengAnbang/Wefore/src/config"
)

func DatabaseBackupsHttp() (string, error) {
	backupPath := code.DatabaseRootPath + time.Now().Format("20060102_150304") + ".sql"
	order := fmt.Sprintf("mysqldump -h%s -P%s -u%s -p%s %s > %s",
		config.ConfigBean.DatabaseAddress,
		config.ConfigBean.DatabasePort,
		config.ConfigBean.DatabaseUserName,
		config.ConfigBean.DatabasePassWord,
		config.ConfigBean.DatabaseName,
		backupPath,
	)
	buffer := bytes.NewBuffer(nil)
	cmd := exec.Command("cmd")
	cmd.Stdin = buffer
	go func() {
		buffer.WriteString(order + "\n")
	}()
	if opBytes, err := cmd.Output(); err != nil {
		return "", errors.New(string(opBytes))
	}
	return backupPath, nil
}

func DatabaseRestoreHttp(path string) (error) {
	order := fmt.Sprintf("mysql -h%s -P%s -u%s -p%s %s < %s",
		config.ConfigBean.DatabaseAddress,
		config.ConfigBean.DatabasePort,
		config.ConfigBean.DatabaseUserName,
		config.ConfigBean.DatabasePassWord,
		config.ConfigBean.DatabaseName,
		path,
	)
	buffer := bytes.NewBuffer(nil)
	cmd := exec.Command("cmd")
	cmd.Stdin = buffer
	go func() {
		buffer.WriteString(order + "\n")
	}()
	if opBytes, err := cmd.Output(); err != nil {
		return errors.New(string(opBytes))
	}
	return nil
}
